<template>
  <div class="jobView" ref="jobViewRef">
    <!-- 头部 -->
    <div class="u-button-div">
      <el-tooltip content="执行" placement="bottom" effect="light">
        <el-button class="u-button" @click="handleRunClick" :disabled="state.button.runDisabled">
          <svg-icon icon-class="icon-run"></svg-icon>
        </el-button>
      </el-tooltip>
      <el-tooltip content="停止" placement="bottom" effect="light">
        <el-button class="u-button" @click="handleStopClick" :disabled="state.button.stopDisabled">
          <svg-icon icon-class="icon-stop"></svg-icon>
        </el-button>
      </el-tooltip>
    </div>
    <div class="work-area">
      <!-- 画布 -->
      <div style="overflow: auto;outline: none;"
        id="graph-container" :style="{ height: domHeight - bottomHeight + 'px'}"
        ref="graphContainerRef">
      </div>
      <!-- 控制台 -->
      <div class="u-footer" :style="{height: bottomHeight + 'px'}">
        <el-tabs>
          <!-- <el-tab-pane label="执行历史"></el-tab-pane> -->
          <el-tab-pane label="日志">
            <div  class="u-footer-log">
              <el-input
                type="textarea"
                readonly
                resize = "none"
                v-model="state.consoleD.logText"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="作业度量">
            <el-table
              class="u-tab-table"
              ref="tabTable"
              :data="state.consoleD.metricData"
              height="200"
              stripe
              row-key="name"
              border
              default-expand-all
              tooltip-effect="dark"
              :tree-props="{ children: 'children' }">
              <el-table-column v-if="(state.consoleD.metric.index !== false)"
                fixed
                type="index"
                width="50"
                header-align="center"
                align="center">
              </el-table-column>
              <template v-for="(column, index) in state.consoleD.metric.columns">
                <el-table-column v-if="((!column.type || column.type==='normal') && (column.visible!==false) && index < consoleD.metric.columns.length-1)"
                  :key="index"
                  :prop="column.prop"
                  :label="column.label"
                  width="140"
                  :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column v-if="((index === state.consoleD.metric.columns.length-1) && (column.visible!==false))"
                  :key="index"
                  :prop="column.prop"
                  :label="column.label"
                  min-width="140"
                  :show-overflow-tooltip="true">
                </el-table-column>
              </template>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
/* eslint-disable new-cap */
import API from '../../api/index'
import * as studio from '../handler/studio-handler'
// 全局常量
import * as global from '../common/common'
import { nextTick, reactive, ref, toRefs, watch, defineEmits, onMounted, h, computed, onUpdated  } from "vue";
import { message, Modal } from 'ant-design-vue';
import tableJson from '../common/job-metrics-table.json'
// import * as mxInit from '@/views/modules/studio/graph/graph.js';
let _self = null

const state = reactive({
  consoleD: {
    logText: '',
    metric: [],
    metricData: [],
    execute: null, // 接收定时器
    executeStatus: false // 执行状态
  },
  containerImagePath: global.CONTAINER_IMAGE_PATH,
  pluginNameMap: new Map(),
  graph: null, // 保存mxGraph对象
  containerStyle: { // 画布样式
    background: 'url(' + (global.CONTAINER_IMAGE_PATH) + ')',
    minHeight: ''
  },
  button: {
    runDisabled: false, // 控制执行按钮点击
    stopDisabled: true // 控制停止按钮点击
  },
  editFlag: false // 流程修改标记
});

const executeStatus = computed(()=> {
  return state.consoleD.executeStatus
})
const domHeight = computed(() => {
  return this.$store.state.common.documentClientHeight - 90
})
const bottomHeight = computed(()=> {
  return 258;
})

watch(executeStatus, ()=> {
  clearInterval(state.consoleD.execute)
})

const graphContainerRef = ref();
const outlineRef = ref();

const setGraph = (graph:any) => {
  state.graph = graph
};
const setThis = (value:any) => {
  _self = value
};
// 执行
const handleRunClick = async () => {
  // 获取xml
  const xml = await studio.getMxGraphXml(state.graph)
  handlerJobRun(xml)
  // 设置当前标签页不可关闭 执行按钮不可点 停止按钮可点
  setStatus('run', true, false)
};
// 作业执行
const handlerJobRun = (xml:any) => {
  resetJob()
  // 根据xml执行转换
  API.job.run(xml).then(res => {
    const resultStatus = res.status + ''
    if (resultStatus.substring(0, 1) === '2') {
      // 获取执行日志
      const executionId = res.data.executionId
      if (executionId) {
        // 获取执行结果
        // this.jobExecuteResult(executionId);
        // 调用定时器
        jobExecuteTimer(executionId)
      } else {
        // 设置当前标签页可关闭 执行按钮可点 停止按钮置灰
        setStatus('run', false, true)
      }
    } else {
      message.warning(res.data.error.message)
      // 清除定时器
      clearInterval(state.consoleD.execute)
      // 设置当前标签页可关闭 执行按钮可点 停止按钮置灰
      setStatus('run', false, true)
    }
  })
};
// 作业调用执行结果定时器
const jobExecuteTimer = (executionId:any) => {
  state.consoleD.execute = window.setInterval(() => {
    jobExecuteResult(executionId)
  }, global.METRICS_INTERVAL)
};
// 获取作业执行结果
const jobExecuteResult = (executionId:any) => {
  const params = {
    executionId: executionId
  }
  API.job.executeResult(params)
  .then(res => {
    // 处理返回的日志数据并显示
    state.consoleD.logText = res.data.logging
    // 处理度量数据并显示
    state.consoleD.metricData = res.data.metrics
    // 显示组件的执行状态
    studio.changePluginState(res.data.status, state.graph)
    // 执行状态
    state.consoleD.executeStatus = res.data.finished
    console.log(state.consoleD.executeStatus)
    if (state.consoleD.executeStatus) {
      // 设置当前标签页可关闭 执行按钮可点 停止按钮置灰
      setStatus('run', false, true)
    }
  })
  .catch(error => {
    const errorResultData = error.response.data
    // 清除定时器
    clearInterval(state.consoleD.execute)
    message.warning(errorResultData.error.message)
    // 设置当前标签页可关闭 执行按钮可点 停止按钮置灰
    setStatus('run', false, true);
  })
};
/**
 * @param {Object} button 按钮类别 （run, stop, pause）
 * @param {Object} buttonStatus 按钮可点击属性值
 * @param {Object} closeStatus 父组件中tab标签页的关闭属性
 */
const setStatus = (button:any, buttonStatus:any, closeStatus:any) => {
  // 设置当前标签页可关闭
  _self.tab.active.closable = closeStatus
  if (button === 'run') {
    // 执行按钮可点 停止 暂停按钮置灰
    state.button.runDisabled = buttonStatus
    state.button.stopDisabled = !buttonStatus
  } else if (button === 'stop') {
    state.button.stopDisabled = buttonStatus
    state.button.runDisabled = !buttonStatus
  }
};
// 重置作业控制台数据
const resetJob = () => {
  // 清空日志
  state.consoleD.logText = ''
  // 清空步骤度量列表数据
  state.consoleD.metricData = []
  // 重置执行状态
  state.consoleD.executeStatus = false
  // 清空组件执行状态图片
  studio.clearPluginOverlays(state.graph)
};
// 停止执行
const handleStopClick = () => {
  // 设置当前标签页可关闭 停止按钮不可点 执行按钮可点
  setStatus('stop', true, true)
};
/**
 * 初始化
 */
const init = async () => {
  // 加载作业度量列表字段
  state.consoleD.metric = tableJson;
};

onMounted (()=> {
  nextTick(() => {
    init()
  })
});

const jobViewRef = ref()
defineExpose({
  graphContainerRef,
  init,
  jobViewRef
})

</script>
<style lang="less" scoped>
.jobView {
  display: flex;
  flex-direction: column;
  .u-button-div {
    height: 40px;
    padding: 0 5px 0 5px;
    line-height: 40px;
    .u-button {
      padding: 5px 12px;
    }
  }
  .work-area {
    .u-footer {
      // width: 100%;
      -webkit-margin-end: 5px;
      -moz-margin-end: 13px;
      .el-tabs--border-card {
        height: 100%;
        width: 100%;
        border-left: none;
        .el-tabs__content {
          padding: 6px !important;
        }
      }
      .u-footer-log {
        height: 195px !important;
        // padding-right: 15px;
        .el-textarea__inner {
          height: 195px;
        }
      }
    }
  }
}
</style>
